package com.qf.system.login.controller;



import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.qf.system.area.model.Area;
import com.qf.system.area.service.AreaService;
import com.qf.system.menu.model.Menu;
import com.qf.system.menu.service.MenuService;
import com.qf.system.param.service.ParamService;
import com.qf.system.role.model.Role;
import com.qf.system.role.service.RoleService;
import com.qf.system.user.model.SystemUser;
import com.qf.system.user.service.SystemUserServiceImpl;
import com.qf.util.PageData;
import com.qf.util.RightsHelper;
import com.qf.util.common.Const;
import com.qf.util.common.DateUtil;
import com.qf.util.common.Tools;
import com.qf.util.controller.BaseController;
import com.qf.util.entity.Page;

/*
 * 总入口
 */
@Controller
public class LoginController extends BaseController {

	@Resource(name="systemuserService")
	private SystemUserServiceImpl userService;
	@Resource(name="menuService")
	private MenuService menuService;
	@Resource(name="roleService")
	private RoleService roleService;
	@Resource(name="paramService")
	private ParamService paramService;
	@Resource(name="areaService")
	private AreaService areaService;
	/**
	* getUQX(获取用户权限)
	* TODO(获取session中的用户名及用户ID)
	* TODO(根基用户名查询用户)
	* TODO(根据用户role_id 查询用户权限)
	* TODO(返回用户权限,并记录登录IP)
	* @param name
	* @param @return 设定文件
	* @return Map<String, String>
	* @Exception 异常对象
	* @since  CodingExample　Ver(编码范例查看) 1.1
	*/
	@SuppressWarnings("unused")
	public Map<String, String> getUQX(Session session){
		PageData pd = new PageData();
		Map<String, String> map = new HashMap<String, String>();
		try {
			String USERNAME = session.getAttribute(Const.SESSION_USERNAME).toString();
			SystemUser UserId=(SystemUser)session.getAttribute(Const.SESSION_USER);
			pd.put("user_name", USERNAME);
			pd=userService.findByUId(pd);
			String ROLE_ID=pd.getString("role_id");
			pd.put("role_id", ROLE_ID);
			
			
			pd = roleService.findObjectById(pd);																
				
		
			
			map.put("add", pd.getString("add_qx"));
			map.put("del", pd.getString("del_qx"));
			map.put("edit", pd.getString("edit_qx"));
			map.put("cha", pd.getString("cha_qx"));
			
			//System.out.println(map);
			
			this.getRemortIP(USERNAME);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}	
		return map;
	}
	/* ==================================================登录过滤========================================================== */
	
	/* ==================================================登录过滤========================================================== */
	
	
	
	/**
	* getRemortIP(获取登录用户的IP)
	* TODO(获取登录IP)
	* TODO(接收用户名)
	* TODO(将用户登录IP修改为当前IP)
	* @param name
	* @param @return 设定文件
	* @return String DOM对象
	* @Exception 异常对象
	* @since  CodingExample　Ver(编码范例查看) 1.1
	*/
	public void getRemortIP(String USERNAME) throws Exception {  
		PageData pd = new PageData();
		HttpServletRequest request = this.getRequest();
		String ip = "";
		if (request.getHeader("x-forwarded-for") == null) {  
			ip = request.getRemoteAddr();  
	    }else{
	    	ip = request.getHeader("x-forwarded-for");  
	    }
		pd.put("user_name", USERNAME);
		pd.put("ip", ip);
		userService.saveIP(pd);
	}  
	
	
	
	/**
	* toLogin(跳转到登录页面)
	* @param name
	* @param @return 设定文件
	* @return ModelAndView
	* @Exception 异常对象
	* @since  CodingExample　Ver(编码范例查看) 1.1
	*/
	@RequestMapping(value="/login_toLogin")
	public ModelAndView toLogin(HttpServletRequest request)throws Exception{
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
//		setParam(request);
		String ip = "";
		if (request.getHeader("x-forwarded-for") == null) {  
			ip = request.getRemoteAddr();  
	    }else{
	    	ip = request.getHeader("x-forwarded-for");  
	    }
		System.out.println(ip+"地址");
		mv.setViewName("/WEB-INF/system/admin/login");
		mv.addObject("pd",pd);
		return mv;
	}
	
	/**
	* login(请求登录，验证用户)
	* TODO(接收前台传入的用户名,密码,验证码)
	* TODO(获取shiro管理的session)
	* TODO(读取session中的验证码)
	* TODO(判断前台传入验证码是否为空)
	* TODO(判断session中的验证码是否为空,并比较前台传入的验证码和session中的验证码)
	* TODO(判断错误则返回登录页面)
	* TODO(判断用户名密码是否正确)
	* TODO(正确则在session中放置用户信息,并跳转到后台)
	* TODO(错误返回错误信息)
	* @param name
	* @param @return 设定文件
	* @return ModelAndView
	* @Exception 异常对象
	* @since  CodingExample　Ver(编码范例查看) 1.1
	*/
	@RequestMapping(value="/login_login"  , method= RequestMethod.POST)
	public ModelAndView login(String loginname,String password,String code)throws Exception{
		ModelAndView mv = this.getModelAndView();
		
		//shiro管理的session
		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		String sessionCode = (String)session.getAttribute(Const.SESSION_SECURITY_CODE);		//获取session中的验证码
		SystemUser u = null;
		String errInfo = "";
		String codes = code;
		if(null == codes || "".equals(codes)){
			mv.setViewName("redirect:/login_toLogin");
		}else{
			String USERNAME = loginname;
			String PASSWORD  = password;
			System.out.println("进入登录方法，用户名："+USERNAME+"密码:"+PASSWORD);
		//	pd.put("USER_NAME", USERNAME);
			if(Tools.notEmpty(sessionCode) && sessionCode.equalsIgnoreCase(codes)){
				
				String passwd = new SimpleHash("SHA-1", USERNAME, PASSWORD).toString();	//密码加密
				Map<String,String> us=new HashMap<String, String>();
				us.put("user_name", USERNAME);
				us.put("password",passwd);
				 u = userService.getUserByNameAndPwd(us);
				if(u != null){
				//	pd.put("LAST_LOGIN",DateUtil.getTime().toString());
					u.setLast_login(DateUtil.getTime().toString());
					userService.updateLastLogin(u);
					List<Area> list=areaService.getProList();
					session.setAttribute(Const.PROVINCE, list);
					session.setAttribute(Const.SESSION_USER, u);
					session.setAttribute("USER_ID",u.getUser_id());
					session.setAttribute(Const.SESSION_USERNAME, u.getUser_name());//用户名
					session.removeAttribute(Const.SESSION_SECURITY_CODE);
					System.out.println(session.getAttribute(Const.SESSION_USERNAME)+"sessionUserNmae");
			
					Subject subject = SecurityUtils.getSubject(); 
				    UsernamePasswordToken token = new UsernamePasswordToken(USERNAME, PASSWORD); 
				    try { 
				        subject.login(token); 
				    } catch (AuthenticationException e) { 
				    	errInfo = "身份验证失败！";
				    }
				    
				}else{
					errInfo = "用户名或密码有误！";
				}
			}else{
				errInfo = "验证码输入有误！";
			}
			if(Tools.isEmpty(errInfo)){
				mv.setViewName("redirect:/qjqwmain/index");
			}else{
				mv.addObject("errInfo", errInfo);
				mv.addObject("loginname",USERNAME);
				mv.addObject("password",PASSWORD);
				mv.setViewName("/WEB-INF/system/admin/login");
			}
		mv.addObject("user",u);
		}
		return mv;
	}
	
	
	/**
	* login_index(访问系统首页)
	* TODO(获取shiro管理的session)
	* TODO(获取session中的用户)
	* TODO(失败则跳转到登录页面,成功继续)
	* TODO(获取session中是否存有用户权限)
	* TODO(如果没有则获取用户权限)
	* TODO(将用户权限放入session)
	* TODO(根据session中的用户权限初始化该用户菜单)
	* TODO(拆分菜单并返回菜单列表和按钮权限)
	* TODO(session失效则跳转到登录页面)
	* @param name
	* @param @return 设定文件
	* @return String DOM对象
	* @Exception 异常对象
	* @since  CodingExample　Ver(编码范例查看) 1.1
	*/
	@SuppressWarnings("unchecked")
	@RequestMapping(value="/qjqwmain/index")
	public ModelAndView login_index(){
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try{
			
			//shiro管理的session
			Subject currentUser = SecurityUtils.getSubject();  
			Session session = currentUser.getSession();
			
			SystemUser systemUser = (SystemUser)session.getAttribute(Const.SESSION_USER);
			if (systemUser != null) {
				
				SystemUser userr = (SystemUser)session.getAttribute(Const.SESSION_USERROL);
				if(null == userr){
					
					systemUser = userService.getUserAndRoleById(systemUser.getUser_id());
					session.setAttribute(Const.SESSION_USERROL, systemUser);
				}else{
					systemUser = userr;
				}
				Role role = systemUser.getRole();
				String roleRights = role!=null ? role.getRights() : "";
				//避免每次拦截用户操作时查询数据库，以下将用户所属角色权限、用户权限限都存入session
				session.setAttribute(Const.SESSION_ROLE_RIGHTS, roleRights); 		//将角色权限存入session
			//	session.setAttribute(Const.SESSION_USERNAME, user.getUSER_NAME());	//放入用户名
				
		        List<Menu> allmenuList = new ArrayList<Menu>();
				
				if(null == session.getAttribute(Const.SESSION_allmenuList)){
					allmenuList = menuService.listAllMenu();
					if(Tools.notEmpty(roleRights)){
						for(Menu menu : allmenuList){
							menu.setHasMenu(RightsHelper.testRights(roleRights, menu.getMenu_id()));
							if(menu.isHasMenu()){
								List<Menu> subMenuList = menu.getSubMenu();
								if(subMenuList!=null){
								for(Menu sub : subMenuList){
									sub.setHasMenu(RightsHelper.testRights(roleRights, sub.getMenu_id()));
								}
								}
							}
						}
					}
					session.setAttribute(Const.SESSION_allmenuList, allmenuList);			//菜单权限放入session中
				}else{
					allmenuList = (List<Menu>)session.getAttribute(Const.SESSION_allmenuList);
				}
				
				//切换菜单=====
				List<Menu> menuList = new ArrayList<Menu>();
				if(null == session.getAttribute(Const.SESSION_menuList) ){
					List<Menu> menuList1 = new ArrayList<Menu>();
					
					//拆分菜单
					for(int i=0;i<allmenuList.size();i++){
						if("0".equals(allmenuList.get(i).getParent_id())){
						Menu menu = allmenuList.get(i);
						List<Menu>  lm=menuService.listSubMenuByParentId(menu.getMenu_id());
						for(int k=0;k<lm.size();k++){
							lm.get(k).setHasMenu(RightsHelper.testRights(roleRights, lm.get(k).getMenu_id()));
						}
						menu.setSubMenu(lm);
							menuList1.add(menu);
						}
					}
					
					session.removeAttribute(Const.SESSION_menuList);
						session.setAttribute(Const.SESSION_menuList, menuList1);
						session.removeAttribute("changeMenu");
						session.setAttribute("changeMenu", "2");
						menuList = menuList1;
				}else{
					menuList = (List<Menu>)session.getAttribute(Const.SESSION_menuList);
				}
				//切换菜单=====
				
				if(null == session.getAttribute(Const.SESSION_QX)){
					session.setAttribute(Const.SESSION_QX, this.getUQX(session));	//按钮权限放到session中
				}
				
			 	
				mv.setViewName("/WEB-INF/system/admin/index");
				mv.addObject("user", systemUser);
				mv.addObject("menuList", menuList);
			}else {
				mv.setViewName("/WEB-INF/system/admin/login");//session失效后跳转登录页面
			}
			
			
		} catch(Exception e){
			mv.setViewName("/WEB-INF/system/admin/login");
			logger.error(e.getMessage(), e);
		}
		mv.addObject("pd",pd);
		return mv;
	}
	

	
	/**
	* defaultPage(登录后台显示的默认页面)
	* TODO(需要显示的信息将在此处初始化)
	* @param name
	* @param @return 设定文件
	* @return String DOM对象
	* @Exception 异常对象
	* @since  CodingExample　Ver(编码范例查看) 1.1
	*/
	@RequestMapping(value="/login_default")
	public String defaultPage(){
		return "/WEB-INF/system/admin/default";
	}
	

	
	/**
	* logout(用户注销方法)
    * TODO(清除session中的用户信息)
    * TODO(注销shiro Subject)
    * TODO(跳转到登录页)
	* @param name
	* @param @return 设定文件
	* @return String DOM对象
	* @Exception 异常对象
	* @since  CodingExample　Ver(编码范例查看) 1.1
	*/
	@RequestMapping(value="/qjqwmain/logout")
	public ModelAndView logout(){
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		
		//shiro管理的session
		Subject currentUser = SecurityUtils.getSubject();  
		Session session = currentUser.getSession();
		
		session.removeAttribute(Const.SESSION_USER);
		session.removeAttribute(Const.SESSION_ROLE_RIGHTS);
		session.removeAttribute(Const.SESSION_allmenuList);
		session.removeAttribute(Const.SESSION_menuList);
		session.removeAttribute(Const.SESSION_QX);
		session.removeAttribute(Const.SESSION_userpds);
		session.removeAttribute(Const.SESSION_USERNAME);
		session.removeAttribute(Const.SESSION_USERROL);
		session.removeAttribute("changeMenu");
		
		//shiro销毁登录
		Subject subject = SecurityUtils.getSubject(); 
		subject.logout();
		
		pd = this.getPageData();
		String  msg = pd.getString("msg");
		pd.put("msg", msg);
		
		mv.setViewName("/WEB-INF/system/admin/login");
		mv.addObject("pd",pd);
		return mv;
	}
	
	
//	public void setParam(HttpServletRequest request){
//        if(request.getSession().getServletContext().getAttribute("SYSNAME")!=null||!request.getSession().getServletContext().getAttribute("SYSNAME").equals("")){
//	    List<Param> pmlist=paramService.listAll();
//		for(Param pm:pmlist){
//			switch(pm.getParamName()){
//			case "SYSNAME":
//				request.getSession().getServletContext().setAttribute("SYSNAME", pm.getParamValue());
//				break;
//			case "seodescription":
//				request.getSession().getServletContext().setAttribute("seodescription",pm.getParamValue());
//				break;
//			case "seokeywords":
//				request.getSession().getServletContext().setAttribute("seokeywords", pm.getParamValue());
//				break;
//				
//			}
//		}
//        }
//	}
}
